package com.sczmgk.hotline.msc;

import android.content.Context;
import android.os.Bundle;

import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.RecognizerListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechRecognizer;
import com.iflytek.cloud.SpeechUtility;
import com.sczmgk.hotline.constant.Constant;
import com.sczmgk.hotline.utils.MyLog;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.LinkedHashMap;

public class MscUtils {
	private MscUtils(){};
	public static MscUtils mscUtils;
	public static MscUtils getInstance(){
		if(mscUtils == null){
			mscUtils = new MscUtils();
		}
		return mscUtils;
	}
	private final  String TAG = MscUtils.class.getSimpleName();
	private   onResustCallback resustCallback;
	/**
	 *  用HashMap存储听写结果
	 */
	private static HashMap<String, String> mIatResults = new LinkedHashMap<String, String>();
	/** 
	 * 引擎类型
	 */
	private static String mEngineType = SpeechConstant.TYPE_CLOUD;
	/**
	 * 参数设置
	 * 
	 * @param mIat
	 * @return
	 */
	public static void  setParam(SpeechRecognizer mIat) {
		// 清空参数
		mIat.setParameter(SpeechConstant.PARAMS, null);

		// 设置听写引擎
		mIat.setParameter(SpeechConstant.ENGINE_TYPE, mEngineType);
		// 设置返回结果格式
		mIat.setParameter(SpeechConstant.RESULT_TYPE, "json");

//		String lag = mSharedPreferences.getString("iat_language_preference","mandarin");
		
		String lag ="mandarin";	
		if (lag.equals("en_us")) {
			// 设置语言
			mIat.setParameter(SpeechConstant.LANGUAGE, "en_us");
		} else {
			// 设置语言
			mIat.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
			// 设置语言区域
			mIat.setParameter(SpeechConstant.ACCENT, lag);
		}

		// 设置语音前端点:静音超时时间，即用户多长时间不说话则当做超时处理
//		mIat.setParameter(SpeechConstant.VAD_BOS, mSharedPreferences.getString("iat_vadbos_preference", "4000"));
		mIat.setParameter(SpeechConstant.VAD_BOS, "4000");
		// 设置语音后端点:后端点静音检测时间，即用户停止说话多长时间内即认为不再输入， 自动停止录音
//		mIat.setParameter(SpeechConstant.VAD_EOS, mSharedPreferences.getString("iat_vadeos_preference", "1000"));
		mIat.setParameter(SpeechConstant.VAD_EOS, "2000");
		// 设置标点符号,设置为"0"返回结果无标点,设置为"1"返回结果有标点
//		mIat.setParameter(SpeechConstant.ASR_PTT, mSharedPreferences.getString("iat_punc_preference", "1"));
		mIat.setParameter(SpeechConstant.ASR_PTT, "0");
		// 设置音频保存路径，保存音频格式支持pcm、wav，设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
		// 注：AUDIO_FORMAT参数语记需要更新版本才能生效
//		mIat.setParameter(SpeechConstant.AUDIO_FORMAT,"wav");
//		mIat.setParameter(SpeechConstant.ASR_AUDIO_PATH, Environment.getExternalStorageDirectory()+"/msc/iat.wav");
		
		// 设置听写结果是否结果动态修正，为“1”则在听写过程中动态递增地返回结果，否则只在听写结束之后返回最终结果
		// 注：该参数暂时只对在线听写有效
//		mIat.setParameter(SpeechConstant.ASR_DWA, mSharedPreferences.getString("iat_dwa_preference", "0"));
		mIat.setParameter(SpeechConstant.ASR_DWA, "0");
	}
	private RecognizerListener recognizerListener = new RecognizerListener() {

		@Override
		public void onVolumeChanged(int arg0, byte[] arg1) {
			MyLog.d(TAG,"音量变化了     arg0 :   "+arg0+"    arg1:  "+arg1[0]);
			if(resustCallback !=null){
				resustCallback.onVolumeChanged(arg0);
			}
			

		}

		@Override
		public void onResult(RecognizerResult results, boolean arg1) {
			String resultString = results.getResultString();
			String parseIatResult = MscJsonParser.parseIatResult(resultString);
			
			MyLog.i(TAG,"取到识别的结果"+parseIatResult);
			printResult(results);
		}

		@Override
		public void onEvent(int arg0, int arg1, int arg2, Bundle arg3) {

			MyLog.i(TAG,"onEvent-------------");
		}

		@Override
		public void onError(SpeechError arg0) {
			MyLog.e(TAG,"识别错误: "+arg0.getErrorCode());
			if (resustCallback != null){
				resustCallback.onError(arg0.getErrorCode());
			}
		}

		@Override
		public void onEndOfSpeech() {
			MyLog.i(TAG,"结束说话");

		}

		@Override
		public void onBeginOfSpeech() {
			MyLog.i(TAG,"开始说话");
		}
	};
	public static interface onResustCallback{
		void onResult(String result);
		void onError(int error);
		void onVolumeChanged(int volume);
	}

	/**
	 * 打印整句识别的结果
	 * @param results
	 */
		private  void printResult(RecognizerResult results) {
			String text = MscJsonParser.parseIatResult(results.getResultString());

			String sn = null;
			// 读取json结果中的sn字段
			try {
				JSONObject resultJson = new JSONObject(results.getResultString());
				sn = resultJson.optString("sn");
			} catch (JSONException e) {
				e.printStackTrace();
			}

			mIatResults.put(sn, text);

			StringBuffer resultBuffer = new StringBuffer();
			for (String key : mIatResults.keySet()) {
				resultBuffer.append(mIatResults.get(key));
			}
            if(resustCallback != null){
            	resustCallback.onResult(resultBuffer.toString());
            }
//			mSearchContent.setText(resultBuffer.toString());
//			mSearchContent.setSelection(mSearchContent.length());
		}
		public  void startListening(SpeechRecognizer mIat,onResustCallback resustCallback){
			this.resustCallback = resustCallback;
			mIat.startListening(recognizerListener);
		}
		/**
		 * 初始化语音识别，传入上下文，Appid
		 */
		public void initMsc(Context context) {
			SpeechUtility.createUtility(context, SpeechConstant.APPID +"="+ Constant.MSC_APPID);//注册ID
		}
		/**
		 * 初始化语音识别，传入上下文，Appid
		 */
		public  SpeechRecognizer startMsc(Context context) {
			return SpeechRecognizer.createRecognizer(context, mInitListener);//初始化
		}
		/**
		 * 初始化的监听器
		 */
		private InitListener mInitListener = new InitListener() {

			@Override
			public void onInit(int code) {

				MyLog.d(TAG,"SpeechRecognizer init() code = " + code);
				if (code != ErrorCode.SUCCESS) {
					MyLog.i(TAG, "初始化失败，错误码：" + code);
				}

			}
		};
}
